#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
import re
import subprocess
import time
import urllib.request
import requests
import os.path
import linecache
import sys

class NovelSpider:
    def __init__(self):
        self.session = requests.Session()

    def get_novel(self,url):
        spider = NovelSpider()
        index_html = self.download(url, encoding='utf-8')
        novel_chapter_infos = self.get_chapter_info(index_html)
        return novel_chapter_infos

    def download(self,url, encoding):
        spider = NovelSpider()
        response = self.session.get(url)
        response.encoding = encoding
        html = response.text
        return html

    def user_data_save(self, user_wifi, user_account, user_password, user_ip):
        spider = NovelSpider()
        with open('user_data.dat', mode='w', encoding='utf-8') as f:
            f.write(user_wifi+"\n"+user_account+"\n"+user_password+"\n"+user_ip)

    def user_data_read(self):
        spider = NovelSpider()
        current_wifi = linecache.getline('user_data.dat', 1)
        account = linecache.getline('user_data.dat', 2)
        password = linecache.getline('user_data.dat', 3)
        ip = linecache.getline('user_data.dat', 4)
        return current_wifi, account, password, ip

    def get_chapter_info(self, index_html):
        spider = NovelSpider()
        div = re.findall(r'<script type="text/javascript">.*?</script>', index_html, re.S)
        div1 = re.search('v4ip=.*?;', str(div), flags=0)
        div2 = re.search(r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b", str(div1))
        return div2.group(0)

    def check_ping(self):  # 通过访问百度得到网络是否畅通的判断
            try:
                q = requests.get("http://www.baidu.com", timeout=5)
                m = re.search(r'STATUS OK', q.text)
                if m:
                    return 'ok'
                else:
                    return 'failed'  # 未登录状态
            except:
                return 'failed'  # 未联网状态

    def login_WIFI(self, account, password, ip):  # 根据URL登陆校园网
        spider = NovelSpider()
        try:
            post_url = 'https://wxrz.ouc.edu.cn:802/eportal/portal/login?callback=dr1003&login_method=1&user_account=,0,'+account+'&user_password='+password+'&wlan_user_ip='+ip+'&wlan_user_ipv6=&wlan_user_mac=000000000000&wlan_ac_ip=&wlan_ac_name=&jsVersion=4.1&terminal_type=1&lang=zh-cn&v=8717&lang=zh'# 直接填写GET地址
            urllib.request.urlopen(post_url, timeout=1000)
            return 'ok'
        except urllib.error.URLError as error:
            return 'failed'

    def login_AUTO(self, account, password, ip):  # 根据URL登陆校园网
        spider = NovelSpider()
        try:
            post_url = 'https://wxrz.ouc.edu.cn:802/eportal/portal/login?callback=dr1003&login_method=1&user_account=,0,' + account + '&user_password=' + password + '&wlan_user_ip=' + ip + '&wlan_user_ipv6=&wlan_user_mac=000000000000&wlan_ac_ip=&wlan_ac_name=&jsVersion=4.1&terminal_type=1&lang=zh-cn&v=8717&lang=zh'  # 直接填写GET地址
            urllib.request.urlopen(post_url, timeout=1000)
            return 'ok'
        except urllib.error.URLError as error:
            return 'failed'

    def auto_switch_wifi(self, current_wifi):  # 连接WiFi
        spider = NovelSpider()
        time.sleep(1)
        try:
            res = os.popen("netsh wlan connect name=%s" % current_wifi)
            return 'ok'
        except urllib.error.URLError as error:
            return 'failed'

    def wifi_connect_main(self):
        spider = NovelSpider()
        temp0, __, __, __ = spider.user_data_read()
        __, temp1, __, __ = spider.user_data_read()
        __, __, temp2, __ = spider.user_data_read()
        __, __, __, temp3 = spider.user_data_read()
        temp0 = temp0.replace("\n", "")
        temp1 = temp1.replace("\n", "")
        temp2 = temp2.replace("\n", "")
        temp3 = temp3.replace("\n", "")
        current_wifi = temp0
        account = temp1
        password = temp2
        ip = temp3
        while 1:
            if current_wifi == "OUC-AUTO":
                while True:
                    time.sleep(5)
                    if spider.check_ping() == 'failed':
                        print('网络连接中断，正在尝试重新连接')
                        reu = spider.auto_switch_wifi(current_wifi)
                        if reu == 'ok':
                            print('连接网络成功，正在尝试登录')
                            while True:
                                time.sleep(1)
                                if spider.login_AUTO(account, password, ip) == ('failed'):
                                    print('error')
                                    time.sleep(1)
                                    continue
                                elif spider.login_AUTO(account, password, ip) == ('ok'):
                                    print('succeed2')
                                    break
                                elif spider.login_AUTO(account, password, ip) == (None):
                                    print('wait...')
                                    time.sleep(2)
                                    continue
                                else:
                                    print(spider.login_AUTO())
                                    break
                        elif reu == 'failed':
                            print('连接网络失败，正在重新连接')
                            continue
                        elif spider.check_ping() == 'ok':
                            print('网络连接畅通')
                            time.sleep(3)
                            break
            elif current_wifi == "OUC-WIFI":
                while True:
                    time.sleep(5)
                    if spider.check_ping() == ('failed'):
                        print('网络连接中断，正在尝试重新连接')
                        reu = spider.auto_switch_wifi(current_wifi)
                        if reu == 'ok':
                            print('连接网络成功，正在尝试登录')
                            while True:
                                time.sleep(1)
                                if spider.login_WIFI(account, password, ip) == ('failed'):
                                    print('error')
                                    time.sleep(1)
                                    continue
                                elif spider.login_WIFI(account, password, ip) == ('ok'):
                                    print('succeed1')
                                    break
                                elif spider.login_WIFI(account, password, ip) == (None):
                                    print('wait...')
                                    time.sleep(2)
                                    continue
                                else:
                                    print(spider.login_AUTO())
                                    break
                        elif reu == 'failed':
                            print('连接网络失败，正在重新连接')
                            continue
                    elif spider.check_ping() == 'ok':
                        print('网络连接畅通')
                        time.sleep(3)
                        break


if __name__ == '__main__':
    res = os.path.isfile("user_data.dat")
    if res == True:
        spider = NovelSpider()
        spider.wifi_connect_main()
    elif res == False:
        print("******************************************")
        print("************现在开始初始化程序************")
        print("******************************************")
        print("*************建议连接OUC-WIFI*************")
        print("******************************************")
        wifi_select = input("请选择已经连接的WIFI（A.OUC-WIFI/B.OUC-AUTO）:")
        while 1:
            if wifi_select == 'A':
                user_wifi = 'OUC-WIFI'
                break
            elif wifi_select == 'B':
                user_wifi = 'OUC-AUTO'
                break
            else:
                print('Error Name\n')
                wifi_select = input("请选择已经连接的WIFI（A.OUC-WIFI/B.OUC-AUTO）:")
        novel_url = 'https://wxrz.ouc.edu.cn/'
        user_account = input("请输入账号：")
        user_password = input("请输入密码：")
        spider = NovelSpider()
        user_ip = spider.get_novel(novel_url)
        spider.user_data_save(user_wifi, user_account, user_password, user_ip)
        print("************初始化完毕 重新执行***********")
        time.sleep(3)
        spider = NovelSpider()
        spider.wifi_connect_main()